//
//  GZSegmentContainerViewController.m
//  GZSegmentBar_Example
//
//  Created by Guo Rui on 2018/1/10.
//  Copyright © 2018年 GR. All rights reserved.
//

#import "GZSegmentContainerViewController.h"
#import "GZSegmentBar.h"
#import <GRFMBaseLib/UIView+XMGLayout.h>

@interface GZSegmentContainerViewController ()<UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;

@end

@implementation GZSegmentContainerViewController


- (void)setItems:(NSArray<id<GZSegmentBarModelProtocol>> *)items childViewControllers:(NSArray<UIViewController *> *)childVCs
{
    NSAssert(items.count != 0 || items.count == childVCs.count, @"个数不一致, 请自己检查");
    
    [self.segmentBar setSegmentItems:items];
    
    [self.childViewControllers makeObjectsPerformSelector:@selector(removeFromParentViewController)];
    
    for (UIViewController *vc in childVCs) {
        [self addChildViewController:vc];
    }
    
    self.segmentBar.selectIndex = 0;
}

- (void)viewDidLayoutSubviews
{
    if (self.segmentBar.superview == self.view) {
        CGFloat topMargin = [UIApplication.sharedApplication statusBarFrame].size.height;
        if (self.navigationController) {
            topMargin += 44.f;
        }
        self.segmentBar.frame = CGRectMake(0, topMargin, self.view.width, 40.f);
        
        CGFloat scrollY = CGRectGetMaxY(self.segmentBar.frame);
        CGFloat scrollH = self.view.height - scrollY;
        self.scrollView.frame = CGRectMake(0, scrollY, self.view.width, scrollH);
    }
    else {
        self.scrollView.frame = self.view.bounds;
    }
    
    self.scrollView.contentSize = CGSizeMake(self.childViewControllers.count * self.view.width, 0);
}

#pragma mark - GZSegmentBarDelegate & UIScrollViewDelegate
- (void)segmentBar:(GZSegmentBar *)segmentBar fromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
    UIViewController *vc = [self.childViewControllers objectAtIndex:toIndex];
    vc.view.frame = CGRectMake(toIndex * self.view.width, 0, self.view.width, self.scrollView.height);
    [self.scrollView addSubview:vc.view];
    
    [self.scrollView setContentOffset:CGPointMake(toIndex * self.view.width, 0) animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = ceil(scrollView.contentOffset.x / self.view.width);
    self.segmentBar.selectIndex = index;
}

#pragma mark - Getter
- (UIScrollView *)scrollView
{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.pagingEnabled = YES;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
        [self.view addSubview:_scrollView];
    }
    return _scrollView;
}

- (GZSegmentBar *)segmentBar
{
    if (!_segmentBar) {
        GZSegmentBar *segmentBar = [[GZSegmentBar alloc] init];
        segmentBar.delegate = self;
        [self.view addSubview:segmentBar];
        _segmentBar = segmentBar;
    }
    return _segmentBar;
}


@end
